<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="获奖名称" prop="awardName">
        <el-input v-model="queryParams.awardName" placeholder="请输入获奖名称" />
      </el-form-item>
      <el-form-item label="等级" prop="awardLevel">
        <el-select v-model="queryParams.awardLevel" placeholder="请选择等级">
          <el-option v-for="dict in award_lever" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="学号" prop="studentId">
        <el-input v-model="queryParams.studentId" placeholder="请输入学号" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['awards:awards:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['awards:awards:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="awardsList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" prop="awardId" />
      <el-table-column label="学号" align="center" prop="studentId" />
      <el-table-column label="获奖名称" align="center" prop="awardName" />
      <el-table-column label="等级" align="center" prop="awardLevel">
        <template #default="scope">
          <dict-tag :options="award_lever" :value="scope.row.awardLevel" />
        </template>
      </el-table-column>
      <el-table-column label="获奖日期" align="center" prop="awardDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.awardDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="awardPhotoPath" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.awardPhotoPath" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['awards:awards:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['awards:awards:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改获奖信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="awardsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="获奖名称" prop="awardName">
          <el-input v-model="form.awardName" placeholder="请输入获奖名称" />
        </el-form-item>
        <el-form-item label="学生学号" prop="awardName">
          <el-input v-model="form.studentId" placeholder="请输入学生学号" />
        </el-form-item>
        <el-form-item label="等级" prop="awardLevel">
          <el-select v-model="form.awardLevel" placeholder="请选择等级">
            <el-option v-for="dict in award_lever" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="获奖日期" prop="awardDate">
          <el-date-picker clearable v-model="form.awardDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择获奖日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="图片" prop="imagePath">
          <image-upload v-model="form.awardPhotoPath" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Awards">
import { listAwards, getAwards, delAwards, addAwards, updateAwards, listByTeacherByParams } from "@/api/awards/awards";
import { listByTeacher } from "@/api/awards/awards"
import { getInfo } from '@/api/login'
const { proxy } = getCurrentInstance();
const { award_lever } = proxy.useDict('award_lever');

const awardsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    awardName: null,
    awardLevel: null,
    awardDate: null,
    awardPhotoPath: null
  },
  rules: {
    awardName: [
      { required: true, message: "获奖名称不能为空", trigger: "blur" }
    ],
    awardLevel: [
      { required: true, message: "等级不能为空", trigger: "change" }
    ],
    studentId: [
      { required: true, message: "学生学号不能为空", trigger: "blur" }
    ],
    awardDate: [
      { required: true, message: "获奖日期不能为空", trigger: "blur" }
    ],
    awardPhotoPath: [
      { required: true, message: "照片不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);
const info = ref("");
const infoType = ref(0)
// 获取当前用户信息
async function fetchInfo() {
  try {
    const result = await getInfo(); // 等待函数解析完成
    info.value = result.user.userName;
    if (result.roles[0] == "admin") {
      getListAll()
      infoType.value = 0
    } else {
      infoType.value = 1
      getList()
    }

  } catch (error) {
    console.error(error);
  }
}

// 管理员
function getListAll() {
  loading.value = true;
  listAwards(queryParams.value).then(response => {
    if (response.code === 200) {
      awardsList.value = response.rows;
    }
    loading.value = false;
  });
}

/** 查询获奖信息列表 */
function getList() {
  loading.value = true;
  listByTeacher(info.value).then(response => {
    if (response.length > 0) {
      awardsList.value = response;
    }
    loading.value = false;
  });
}

/** 查询获奖信息列表条件版 */
function getListByParams() {
  loading.value = true;
  listByTeacherByParams(queryParams.value, info.value).then(response => {
    if (response.code == 200) {
      awardsList.value = response.data;
    }
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    awardId: null,
    studentId: null,
    awardName: null,
    awardLevel: null,
    awardDate: null,
    awardPhotoPath: null
  };
  proxy.resetForm("awardsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  if (infoType.value == 0) getListAll()
  if (infoType.value == 1) getListByParams();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.awardId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加获奖信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const _awardId = row.awardId || ids.value
  getAwards(_awardId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改获奖信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["awardsRef"].validate(valid => {
    if (valid) {
      if (form.value.awardId != null) {
        updateAwards(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          fetchInfo()
        });
      } else {
        addAwards(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          fetchInfo();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _awardIds = row.awardId || ids.value;
  proxy.$modal.confirm('是否确认删除获奖信息编号为"' + _awardIds + '"的数据项？').then(function () {
    return delAwards(_awardIds);
  }).then(() => {
    fetchInfo();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('awards/awards/export', {
    ...queryParams.value
  }, `awards_${new Date().getTime()}.xlsx`)
}

fetchInfo();
</script>
